from flask import g, jsonify, render_template, request, current_app, session

from info import db, constants
from info.constants import QINIU_DOMIN_PREFIX
from info.models import News, Category
from info.modules.user import user_blue
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@user_blue.route("/user_info")
@user_login_data
def user_info():
    user = g.user
    # 校验用户是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    data = {
        "user_info": user.to_dict(),
        "avatar_url": QINIU_DOMIN_PREFIX + user.avatar_url if user.avatar_url else None
    }
    return render_template("news/user.html", data=data)


@user_blue.route("/user_base_info", methods=["POST", "GET"])
@user_login_data
def user_base_info():
    user = g.user
    if request.method == "GET":
        return render_template("news/user_base_info.html", data=user.to_dict())
    else:
        # 1、获取数据
        data_json = request.json
        signature = data_json.get("signature")
        nick_name = data_json.get("nick_name")
        gender = data_json.get("gender")
        print("性别", gender)
        if not all([signature, nick_name, gender]):
            return jsonify(errno=RET.DATAERR, errmsg="数据不存在")

        if gender not in (['MAN', 'WOMAN']):
            return jsonify(errno=RET.DATAERR, errmsg="性别数据传输有误")

        try:
            user.nick_name = nick_name
            user.signature = signature
            user.gender = gender
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据保存失败,请稍后再试")
        # 将 session 中保存的数据进行实时更新
        session["nick_name"] = nick_name
        return jsonify(errno=RET.OK, errmsg="数据修改成功")


@user_blue.route("/pic_info", methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        data = {
            "user_info": user.to_dict(),
            "avatar_url": QINIU_DOMIN_PREFIX + user.avatar_url if user.avatar_url else None
        }
        return render_template("news/user_pic_info.html", data=data)

    # 图片获取数据
    try:
        data = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据获取失败")

    # 将图片上传至七牛云服务器
    try:
        image = storage(data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="图片上传失败,请稍后再试！")

    # 将上传的图片路径存储到数据库里
    try:
        user.avatar_url = image
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="图片保存失败,请稍后再试！")

    return jsonify(errno=RET.OK, errmsg="图片保存成功", data={"avatar_url": QINIU_DOMIN_PREFIX + image})


@user_blue.route("/pass_info", methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template("news/user_pass_info.html")
    else:
        print("进入函数")
        # 1、获取参数
        old_password = request.json.get("old_password")
        new_password = request.json.get("new_password")

        print("old_password", old_password)
        print("new_password", new_password)

        # 2、校验参数
        # 2.1校验传入的参数是否有缺失
        if not all([old_password, new_password]):
            return jsonify(errno=RET.DATAERR, errmsg="数据不存在")

        # 2.2校验输入的旧密码是否正确
        print(g.user.check_password(old_password))
        if not g.user.check_password(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="旧密码输入不正确,请确认后再试！")

        # 3、提交数据
        try:
            g.user.password = new_password
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据保存失败,请稍后再试")
        # 返回
        return jsonify(errno=RET.OK, errmsg="密码修改成功")


@user_blue.route("/user_collection")
@user_login_data
def user_collection():
    print("进入函数")
    user = g.user
    # 获取数据
    # 传入需要获取的页数
    p = request.args.get("p", 1)
    # 将获取的页数转换为数字
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        # 如果用户乱传数据，就默认查询第一页数据
        p = 1

    # 对需要返回的值给一个默认值，即使数据库查询无数据也有数据返回，避免前端报错
    page_data = []
    page = 1
    pages = 1
    try:
        pagination = user.collection_news.paginate(page=p, per_page=5, error_out=False)
        # 获取所有数据
        page_data = pagination.items
        # 获取当前页数
        page = pagination.page
        # 获取总页数
        pages = pagination.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败,请稍后再试")

    news_data = []
    for news in page_data:
        news_data.append(news.to_basic_dict())

    print("最终的用户数据", news_data)
    data = {
        "page_data": news_data,
        "page": page,
        "pages": pages

    }
    return render_template("news/user_collection.html", data=data)


@user_blue.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    user = g.user

    if request.method == "GET":
        category_list = []
        try:
            all_category = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="分类数据查询失败")

        for category in all_category[1:]:
            category_list.append(category.to_dict())
        data = {
            "category_list": category_list,
        }
        return render_template("news/user_news_release.html", data=data)

    else:
        # 1、获取参数
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        # 新闻状态，新添加的内容默认状态为审核中
        status = 0

        # 2、校验一下获取的参数是否有缺失
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.DATAERR, errmsg="数据有缺失,请补充后再试")

        # 3、将上传的文件读取出来
        try:
            image = index_image.read()

        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="图片读取失败,请稍后再试")

        # 4、将读取出来的图片上传的七牛云
        try:
            image_name = storage(image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="图片保存失败,请稍后再试")

        # 5、将数据保存到数据库里
        # 实例化数据库
        news = News()
        news.title = title
        news.source = user.nick_name
        news.digest = digest
        news.content = content
        news.index_image_url = QINIU_DOMIN_PREFIX + image_name
        news.category_id = category_id
        news.user_id = user.id
        news.status = status

        try:
            print("执行数据库提交操作")
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="数据储存失败,请稍后再试")

        return jsonify(errno=RET.OK, errmsg="新闻创建成功,审核通过后,会立刻发布！！")


@user_blue.route("/news_list")
@user_login_data
def news_list():
    # 1、获取当前页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user_news_list = []
    try:
        pagination = g.user.news_list.paginate(page=p, per_page=2, error_out=False)
        # 获取分页后的所有数据
        user_news = pagination.items
        # 获取当前页数
        page = pagination.page
        # 获取总页数
        pages = pagination.pages
        for news in user_news:
            user_news_list.append(news.to_review_dict())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻列表查询失败")
    print(user_news_list)
    data = {
        "user_news_list": user_news_list,
        "page": page,
        "pages": pages,
    }

    return render_template("news/user_news_list.html", data=data)


@user_blue.route("/user_follow")
@user_login_data
def user_follow():
    user = g.user
    # 接收传入的参数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        current_app.aborter(404)

    user_follow_all = []
    try:
        pagination = user.followed.paginate(page=p, per_page=1, error_out=False)
        user_follow = pagination.items
        page = pagination.page
        pages = pagination.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="关注用户信息查询失败")

    # 校验数据库是否存在关注的用户
    if not user_follow:
        return render_template("news/user_follow.html", data=user_follow_all)

    for user in user_follow:
        user_follow_all.append(user.to_dict())
    print(user_follow_all)
    data = {
        "user_follow_all": user_follow_all if user_follow_all else [],
        "page": page,
        "pages": pages
    }
    return render_template("news/user_follow.html", data=data)
